package handler

import (
	"sept21-homework/model"
	"strconv"

	"github.com/gin-gonic/gin"
)

func CommentAdd(c *gin.Context) {
	new_id, _ := strconv.Atoi(c.PostForm("new_id"))

	if new_id == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}

	//----------事务----------

	tx := model.DB.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "评论失败",
			})
			return
		}
	}()

	if err := tx.Error; err != nil {
		tx.Rollback()
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "评论失败",
		})
		return
	}

	comment := model.Comment{
		NewId: new_id,
	}
	err := tx.Create(&comment).Debug().Error
	if err != nil {
		tx.Rollback()
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "评论失败",
		})
		return
	}

	err = tx.Commit().Error
	if err != nil {
		tx.Rollback()
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "评论失败",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "评论成功",
		"data": comment,
	})
	return
}
